package com.krtech.wecard.module.weixin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.krtech.wecard.module.weixin.pojo.WxDynamicMenuVo;
import com.krtech.wecard.module.weixin.pojo.WxMenuButtonVo;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import java.util.stream.Collectors;

import com.krtech.wecard.module.weixin.bean.WxDynamicMenu;
import com.krtech.wecard.module.weixin.mapper.WxDynamicMenuMapper;
import com.krtech.wecard.module.weixin.service.WxDynamicMenuService;

@Service
public class WxDynamicMenuServiceImpl extends ServiceImpl<WxDynamicMenuMapper, WxDynamicMenu> implements WxDynamicMenuService {

    @Override
    public int updateBatch(List<WxDynamicMenu> list) {
        return baseMapper.updateBatch(list);
    }

    @Override
    public int batchInsert(List<WxDynamicMenu> list) {
        return baseMapper.batchInsert(list);
    }


    /**
     * 获得当前菜单,数据库实体
     *
     * @return
     */
    @Override
    public List<WxDynamicMenuVo> getCurrentMenuToWxDynamicMenuTree(){
        List<WxDynamicMenu> menuList = this.list();
        List<WxDynamicMenuVo> wxMenuButtonVos = menuToTreeByPidToWxDynamicMenu(menuList, 0);

        return wxMenuButtonVos;
    }

    public static List<WxDynamicMenuVo> menuToTreeByPidToWxDynamicMenu(List<WxDynamicMenu> treeList, Integer pid) {
        List<WxDynamicMenuVo> retList = new ArrayList<>();
        for (WxDynamicMenu parent : treeList) {
            if (pid.equals(parent.getPid())) {
                WxDynamicMenuVo dynamicMenuVo = new WxDynamicMenuVo();
                BeanUtil.copyProperties(parent,dynamicMenuVo);

                retList.add(menufindChildrenByPidToWxDynamicMenu(dynamicMenuVo, treeList));
            }
        }
        return retList;
    }


    private static WxDynamicMenuVo menufindChildrenByPidToWxDynamicMenu(WxDynamicMenuVo parent, List<WxDynamicMenu> treeList) {
        for (WxDynamicMenu child : treeList) {
            Integer parentId = parent.getId();
            Integer pid = child.getPid();
            if (parentId.equals(pid)) {
                if (parent.getChild() == null) {
                    parent.setChild(new ArrayList<>());
                }
                WxDynamicMenuVo childMenu = new WxDynamicMenuVo();
                BeanUtil.copyProperties(child,childMenu);

                parent.getChild().add(menufindChildrenByPidToWxDynamicMenu(childMenu, treeList));
            }
        }
        return parent;
    }
}

